﻿using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using DTO;

namespace DAO
{
    public class PhuongDAO : DataProvider
    {
        protected override object GetDataRowFromDataReader(OleDbDataReader dr)
        {
            PhuongDTO phuongDTO = new PhuongDTO();
            if (!dr.IsDBNull(0))
            {
                phuongDTO.MaPhuong = dr.GetInt32(0);
            }

            if (!dr.IsDBNull(1))
            {
                phuongDTO.TenPhuong = dr.GetString(1);
            }

            return (object)phuongDTO;
        }
        public List<PhuongDTO> GetAllPhuongDTO()
        {
            List<PhuongDTO> lstPhuongDTO = new List<PhuongDTO>();
            try
            {
                string strSQL = @"SELECT *" +
                                @" FROM Phuong";

                using (OleDbDataReader dr = this.ExcuteReader(strSQL))
                {
                    while (dr.Read())
                    {
                        PhuongDTO PhuongDTO = (PhuongDTO)GetDataRowFromDataReader(dr);
                        lstPhuongDTO.Add(PhuongDTO);
                    }
                }
            }
            catch (Exception ex)
            {
                lstPhuongDTO = new List<PhuongDTO>();
            }

            return lstPhuongDTO;
        }
        public PhuongDTO Search(int id)
        {
            PhuongDTO phuongDTO = null;
            try
            {
                string strSQL = @"SELECT *" +
                                @" FROM PHUONG" +
                                @" WHERE MaPhuong = " + id.ToString();

                using (OleDbDataReader dr = this.ExcuteReader(strSQL))
                {
                    if (dr.Read())
                    {
                        phuongDTO = (PhuongDTO)GetDataRowFromDataReader(dr);
                    }
                }
            }
            catch (Exception ex)
            {
                phuongDTO = null;
            }

            return phuongDTO;
        }

        public int GetIdByName(string name)
        {
            int maPhuong = -1;
            try
            {
                string strSQL = @"SELECT MaPhuong" +
                                @" FROM PHUONG" +
                                @" WHERE TenPhuong = '" + name + "'";

                using (OleDbDataReader dr = this.ExcuteReader(strSQL))
                {
                    if (dr.Read())
                    {
                        maPhuong = dr.GetInt32(0);
                    }
                }
            }
            catch (Exception ex)
            {
                maPhuong = -1;
            }

            return maPhuong;
        }
    }
}
